# -*- encoding : utf-8 -*-
# 入口文件

# 获取数据的类
require "remember.rb"
require "lang.rb"
require "config.rb"
require "dynamic_invoke_method"
require "util"

# 引入模块
include Dynamic_invoke_module_method

$lang = Lang[LANG]

  # 文件选取逻辑
  def file_choice(dir_path)
    next_filename = Util.after_last_symbol dir_path
    # 可以精确匹配
    collect_file_path = dir_path + '/' + next_filename  + '.rb'
    return collect_file_path if File.exist? collect_file_path
    dir_path
  end

  # 目录选取逻辑
  def dir_choice(dir_path, file_path, dict)
    next_dir = Util.before_first_symbol(file_path)
    # 可以精确匹配
    pattern_path = dir_path + '/' + next_dir
    return pattern_path if Dir.exist? pattern_path
    # 如果存在路径通配符?，匹配任意目录名
    pattern_path = dir_path + '/*'
    if Dir.exist? pattern_path
      storeSymbolInfo dict,'*',next_dir
      return pattern_path 
    end
    dir_path
  end

  # 通配符转换为module名字
  def analysis_file_name(filename)
    case filename
    when '*' then 'star'
    else filename
    end
  end

  # 存储通配符的替换信息
  def storeSymbolInfo(dict,symbol,value)
    symbol = symbol.to_sym
    if dict.has_key?(symbol)
      list = dict[symbol]
      list << value
    else
      list = [value]
      dict[symbol] = list
    end
  end

if ARGV.size == 0
  puts "no args"
else
  url = ARGV[0].strip.downcase
  uri = URI.parse url
  file_path = Util.uri_path uri
  dir_path = 'collecter'
  collecter_name = dir_path
  pattern_replace_dict = {}
  args = {}
  args["url"] = url
  args["store_path"] = File.expand_path(DATA_STORE) + '/' + file_path
  args["pattern_replace_dict"] = pattern_replace_dict
  # 根据url自动加载抓取数据的脚本并执行
  file_path = file_path + '/'
  while file_path.length > 0
    dir_path = dir_choice dir_path,file_path,pattern_replace_dict
    file_path = Util.after_first_symbol file_path
    collect_file_path = file_choice dir_path
    # 匹配到脚本，加载并执行
    if File.file? collect_file_path
      load collect_file_path
      collecter_name = Util.after_last_symbol collect_file_path 
      collecter_name = Util.before_last_symbol collecter_name,'.'
      collecter_name = analysis_file_name collecter_name
      invoke_module_method collecter_name.capitalize,collecter_name,args
      break
    end
  end
end

